<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <!-- 提示区域 -->
            <el-alert
                title="添加商品信息"
                type="info"
                center
                show-icon
                :closable="false">
            </el-alert>

            <!-- 步骤条区域 -->
            <el-steps :active="0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
                <!-- 左侧tabs区域 -->
                <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabsLeave" @tab-click="tabClicked">
                    <!-- 基本信息右侧表单 -->
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格（元）" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量（千克）" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量（个）" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <!-- 级联选择器 -->
                            <el-cascader
                                v-model="addForm.goods_cat"
                                :options="cateList"
                                :props="cateProps"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>

                    <!-- 商品参数右侧内容 -->
                    <el-tab-pane label="商品参数" name="1">
                      <el-form-item v-for="item in manyTable" :key="item.attr_id" :label="item.attr_name">
                        <!-- 复选框组 -->
                        <el-checkbox-group v-model="item.attr_vals">
                          <el-checkbox :label="item1" v-for="(item1,index) in item.attr_vals" :key="index"></el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>
                    </el-tab-pane>

                    <!-- 商品属性右侧内容 -->
                    <el-tab-pane label="商品属性" name="2">
                      <el-form-item v-for="item in onlyTable" :key="item.attr_id" :label="item.attr_name">
                        <el-input v-model="item.attr_vals"></el-input>
                      </el-form-item>
                    </el-tab-pane>

                    <!-- 商品图片右侧内容 -->
                    <el-tab-pane label="商品图片" name="3">
                      <!-- 图片上传 -->
                      <el-upload
                        class="upload-demo"
                        :action="upload"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        list-type="picture"
                        :headers="headerObj"
                        :on-success="handleSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                      </el-upload>
                    </el-tab-pane>

                    <!-- 商品内容右侧内容 -->
                    <el-tab-pane label="商品内容" name="4">
                      <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                      <el-button type="primary" class="btn" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <!-- 图片预览对话框 -->
        <el-dialog
          title="图片预览"
          :visible.sync="picDialogVisible"
          width="30%">
          <img :src="fileUrl" alt="" class="previewImg">
        </el-dialog>

    </div>
</template>

<script>
export default {
  data() {
    return {
      // 基本信息的表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,

        // 选中分类
        goods_cat: [],

        // 图片数组
        pics: [],

        // 商品详情的介绍
        goods_introduce: '',

        attrs: []
      },

      // 表单验证对象
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },

      // 分类列表
      cateList: [],

      // 分类列表的对象
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },

      // tabs切换
      activeIndex: 0,

      // 存放many参数
      manyTable: [],

      // 存放only参数
      onlyTable: [],

      // 上传图片的地址
      upload: 'http://127.0.0.1:8888/api/private/v1/upload',

      // upload上传请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 预览图片的url地址
      fileUrl: '',

      // 图片预览对话框
      picDialogVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.cateList = res.data
    },

    // 级联选择框改变时触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // tabs标签切换时触发
    beforeTabsLeave(activeName, oldName) {
      if (oldName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择分类')
        return false
      }
    },

    // tabs点击时触发
    async tabClicked() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTable = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        this.onlyTable = res.data
      }
    },

    // 处理图片预览效果
    handlePreview(file) {
      this.fileUrl = file.response.data.url
      this.picDialogVisible = true
    },

    // 处理图片移出效果
    handleRemove(file) {
      const removePath = file.response.data.temp_path
      const fileIndex = this.addForm.pics.findIndex(item => {
        return item.pic === removePath
      })
      this.addForm.pics.splice(fileIndex, 1)
    },

    // 监听图片上传成功
    handleSuccess(response) {
      const picInfo = { pic: response.data.temp_path }
      this.addForm.pics.push(picInfo)
    },

    // 添加商品
    add() {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message('请填写必要的添加选项')
        }
        // 添加业务逻辑
        const objString = JSON.stringify(this.addForm)
        const formDate = JSON.parse(objString)
        formDate.goods_cat = formDate.goods_cat.join(',')
        // 处理动态参数和静态属性
        this.manyTable.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join('') }
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTable.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        formDate.attrs = this.addForm.attrs
        console.log(formDate)
        // 发起请求，添加商品
        const { data: res } = await this.$http.post('goods', formDate)
        console.log(res)
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },

  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
    margin: 40px 0;
}

.previewImg {
  width: 100%;
}

.btn {
  margin-top: 10px
}
</style>
